package com.example.day03_mvp.not;

import android.util.Log;

import com.example.day03_mvp.base.Constants;
import com.example.day03_mvp.utils.SystemUtil;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpUlist {

    private final Retrofit.Builder retrofit;

    public HttpUlist(){
        OkHttpClient okHttpClient = getOkHttpClient();
        retrofit = getRetrofit(okHttpClient);
    }
    public static volatile HttpUlist instance;
    public static HttpUlist getinstance(){
        if (instance==null){
            synchronized (HttpUlist.class){
                if (instance==null){
                    instance=new HttpUlist();
                }
            }
        }
        return instance;
    }
    private Retrofit.Builder getRetrofit(OkHttpClient okHttpClient) {
        return new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
    }

    private OkHttpClient getOkHttpClient() {
        File file = new File(Constants.PATH_CACHE);
        Cache cache = new Cache(file, 1024 * 1024 * 100);
        return new OkHttpClient.Builder()
                .cache(cache)
                .addInterceptor(new MyCacheinterceptor())
                .addNetworkInterceptor(new MyCacheinterceptor())
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60,TimeUnit.SECONDS)
                .writeTimeout(60,TimeUnit.SECONDS)
                .build();
    }
    public synchronized <T> T getApiServer(String url,Class<T> tClass){
        return retrofit.baseUrl(url).build().create(tClass);
    }
    private class  MyCacheinterceptor implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!SystemUtil.isNetworkConnected()){
                 request  = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }
            Response proceed = chain.proceed(request);
            if (SystemUtil.isNetworkConnected()){
                int maxAge=0;
                return proceed.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control","pulic,max-age"+maxAge)
                        .build();
            }else{
                int maxStale=60*60*24;
                proceed.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control","public,only-if-cached,"+"max-stale="+maxStale)
                        .build();
            }
            return null;
        }
    }
    //日志拦截器
    public class LoggingInterceptor implements Interceptor {
        private static final String TAG = "LoggingInterceptor";

        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            //拦截链对象
            Request request = chain.request();
            //Object...args ,...是可变参数,可以理解成数组
            //String.format()第一个参数是格式,后面的参数是替代参数,需要将里面的%s的位置使用
            //后面的参数给替代掉
            //"发送请求地址:"+request.url()+"%n请求头:"+request.header();
            Log.d(TAG, String.format("发送请求地址:%s%n请求头:%s",request.url(),
                    request.headers()));
            long startTime = System.currentTimeMillis();
            //递归+循环的方式把所有的拦截器串联起来,并获取响应结果
            Response response = chain.proceed(request);
            long endTime = System.currentTimeMillis();

            //这里不能直接使用response.body().string()的方式输出日志
            //因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一
            //个新的response给应用层处理
            ResponseBody responseBody = response.peekBody(1024 * 1024);

            Log.d(TAG, String.format("耗时:%s%n收到来自:%s的结果:%n%s",
                    (endTime-startTime)+"ms",response.request().url(),responseBody.string()));

            return response;
        }
    }
}
